var serverHost = "http://10.1.206.90:13110/";
// var serverHost = "http://10.1.203.219:5001/";
// var serverHost = "http://10.1.206.100:5001/";
// var serverHost = "http://10.1.206.101:13108/";
// var serverHost = "http://10.1.203.224:5001/";
var imageType = "base64"; // 显示图片的方式，"name" 为按照图片对应的文件名显示， "base64"按照base64编码字符串显示，	"plotly"是plotly转的html字符串
var pack_results = null;
var current_tr_id = -1;
var current_page = 1
var totalPage = 1
var plotly_3d = false;
var images = [];

var plotHost = "http://10.1.206.90:13110/plot";


var pack = function(items) {

	$.blockUI({
		message: "<span>货物装箱中...</span>",
		css: {
			"font-size": "30px",
			"font-weight": "bold"
		}
	});
	
	let cars = all_routes[$('#route-select').val()];

	clear();

	$.ajax({
		type: "POST",
		url: serverHost + "pack",
		contentType: "application/json",
		dataType: "json",
		// Access-Control-Allow-Credentials: true,
		xhrFields: {
		    withCredentials: true
		  },
		data: JSON.stringify({
			items: items,
			cars: cars,
			config_parameters: config_dict
		}),
		async: true,
		success: function(result) {
			$.unblockUI();
			console.log(result);
			refreshResultTable(result.result); // 更新结果表格
			showCheckList();
		}
	});
}


var setPageView = function(num, k=0) {
	
	// 1. 更新页面
	let liHtml = "";
	let i = 0;
	while (i < num) {
		
		if (i === k) {
			liHtml += `<li class="page-item active" page="${i + 1}"><a class="page-link" href="#">${i + 1}</a></li>`;
		} else {
			liHtml += `<li class="page-item" page="${i + 1}"><a class="page-link" href="#">${i + 1}</a></li>`;
		}
		
		++ i;
		
	}
	$('#page-div').html(`<ul class="pagination m-0 ms-auto">${liHtml}</ul>`);
	
	// 2. 设置事件
	$('.page-item').on('click', function () {
		
		// 2.1 清除所有的active类
		$('.page-item').removeClass("active");
		//  2.2 为点击的item添加active类
		$(this).addClass("active");
		
		current_page = parseInt($(this).attr('page'));
		
		let figure_type = 1;
		if ($('#hot-switch').is(':checked')) {
			figure_type = 2;
		}
		
		let divs = $('.img-div');
		divs.each(function(index, dom) {
		
			if (index < 4) {
				$(dom).find('img').attr('src', `data:image/png;base64,${images[index + (current_page - 1) * 4]}`);
			}
		
		});
		
		// refreshFigures(pack_results[current_tr_id]['heaps'], pack_results[current_tr_id]['packer'], figure_type, plotly_3d);
		
	});
	
}


var refreshResultTable = function(result) {
	
	pack_results = result;


	let tableHtml = "";

	let index = 1;
	let num = 0;
	for (let item of result) {
		let status = item.status;
		num ++;
		if (!status) {
			continue;
		}

		let type = "";
		for (let single of item.bin_type) {
			let t = JSON.parse(single.split('-')[1].replace('(', '[').replace(')', ']'));
			type += `(${t[0]}x${t[1]}x${t[2]}),`;
		}
		type = type.slice(0, type.length - 1);
		tableHtml += `<tr class="pcaking-result-tr" price="${item.price}" 
		bin-volume="${item.bin_volume}" goods-volume="${item.goods_volume}" 
		space-ratio="${item.space_ratio}" box-weight="${item.box_weight}"
		goods-weight="${item.goods_weight}" weight_ratio="${item.weight_ratio}"
		colors='${JSON.stringify(item.color)}' result-id="${num - 1}" car-num="${item['car-num']}">
						<td>${index}</td>
						<td>${type}</td>
						<td>${item.price}元</td>
						<td>${(item.space_ratio * 100).toFixed(2)}%</td>
						<td>${(item.weight_ratio * 100).toFixed(2)}%</td>
					</tr>`;

		index++;

	}

	$('#pcaking-result-table-body').html(tableHtml);

	// 为tr添加点击事件
	$('.pcaking-result-tr').click(function() {
		
		// $('#hot-switch').prop('checked', false);
		
		// 设置页码
		current_page = 1;
		totalPage = parseInt($(this).attr('car-num'));
		setPageView(parseInt($(this).attr('car-num')));

		// 1. 设置样式
		// 1.1 清除所有tr的选中样式
		$('.pcaking-result-tr').removeClass('pcaking-result-tr-selected');

		// 1.2 为选中的tr设置选中样式
		$(this).addClass('pcaking-result-tr-selected');
		
		let c_tr = $(this);
		current_tr_id = parseInt($(this).attr('result-id'));
		
		$('#legend-div').show();

		// 2. 展示图像
		// 2.1 获取图像文件名
		// let imgs = $(this).attr('imgs').split(',');
		// let imgs_base64 = $(this).attr('imgs_bs64').split(',');
		// console.log(imgs_base64.length);
		
		let figure_type = 1;
		if ($('#hot-switch').is(':checked')) {
			figure_type = 2;
		}
		refreshFigures(pack_results[current_tr_id]['heaps'], pack_results[current_tr_id]['packer'], figure_type, plotly_3d);

		// 2.2 绘制图像
		// let divs = $('.img-div');

		// if (imageType === 'name') {
		// 	$('.image_show').show();
		// 	$('.plotly_show').hide();
		// 	divs.each(function(index, dom) {

		// 		if (index < 4) {
		// 			$(dom).find('img').attr('src', `./images/${imgs[index]}.png`);
		// 		}

		// 	});

		// } else if (imageType === 'base64') {
		// 	$('.image_show').show();
		// 	$('.plotly_show').hide();

		// 	divs.each(function(index, dom) {

		// 		if (index < 4) {
		// 			$(dom).find('img').attr('src', `data:image/png;base64,${imgs_base64[index]}`);
		// 		}

		// 	});

		// } else if (imageType === 'plotly') {
			
		// 	$('.image_show').hide();
		// 	$('.plotly_show').show();
			
		// 	let idx = parseInt(c_tr.attr('result-id'));
		// 	$('.plotly_show').html(pack_results[idx]['plotly_html']);
			
		// }

		// 2.3 更新进度条
		let tr = $(this);
		$('#progress-footer').show();
		$('#progress-footer-2').show();
		$('#total-volume').text(`${tr.attr('bin-volume')}升`);
		$('#total-cost').text(`${tr.attr('price')}元`);
		$('#goods-volume').css('width', `${(tr.attr('space-ratio') * 100).toFixed(2)}%`);
		$('#text-goods-volume').text(parseFloat(tr.attr('goods-volume')).toFixed(2) + "升");
		$('#text-free-volume').text(parseFloat(tr.attr('bin-volume') - tr.attr('goods-volume')).toFixed(2) +
			"升");

		$('#total-weight').text(tr.attr('box-weight') + "千克");
		$('#goods-weight').css('width', `${(tr.attr('weight_ratio') * 100).toFixed(2)}%`)
		$('#text-goods-weight').text(tr.attr('goods-weight') + "千克");
		$('#text-free-weight').text(tr.attr('box-weight') - tr.attr('goods-weight') + "千克");

		// 2.4 更新legends
		// let legends_html = "";
		// // let colors = JSON.parse(tr.attr('colors'));
		// for (let item_size in colors) {
		// 	let color = colors[item_size];
		// 	let radius = parseFloat(item_size.split('-')[0]) / 2;
		// 	let size_str =
		// 		`${parseFloat(item_size.split('-')[0]) / 2} x ${parseFloat(item_size.split('-')[1])}`;
		// 	// console.log(radius, color);
		// 	legends_html += `<div>
		// 						<svg viewBox="0 0 40 40" width="40" height="40">
		// 							<circle class="circle" cx="10" cy="20" r="${radius * 1.8}" fill="${color}"/>
		// 						</svg>
		// 						${size_str}
		// 					</div>`;
		// 	// legends_html += `<div>
		// 	// 					<svg t="1702347737599" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4660" width="400" height="400">
		// 	// 						<path cx=512 cy=512 d="M66.55762719 705.82428687c-37.77114-91.06602094-42.91276125-250.30796156-11.56864782-355.66175718s87.40756031-116.97188156 125.17870032-25.90586063 42.91276125 250.30796156 11.56864781 355.66175719-87.40756031 116.92244343-125.17870031 25.90586062z" fill="${color}" p-id="4661"></path>
		// 	// 						<path d="M902.565455 761.09671438c-20.66536218 0-41.57791781-19.77546562-58.73313469-61.35338344-37.77114-91.06602094-42.91276125-250.30796156-11.56864781-355.66175719C849.36945124 286.58440625 873.84159031 257.02008406 898.70923907 256.82232969l-777.27469407 6.08095594c-24.71933251 0-49.438665 29.66319938-66.44556562 87.25924406-31.3935525 105.35379563-26.20249219 264.59573625 11.56864781 355.66175719 17.15521689 41.3801625 38.0677725 61.5511378 58.73313374 61.35338343z" fill="${color}" p-id="4662"></path>
		// 	// 						<path d="M863.684005 699.74333093c-37.77114-91.06602094-42.91276125-250.30796156-11.56864782-355.66175718S939.67123281 227.15913031 977.39293468 318.17571313s42.96220031 250.30796156 11.61808595 355.66175718S901.55402218 790.80935188 863.684005 699.74333093z" fill="${color}" p-id="4663"></path>
		// 	// 					</svg>
		// 	// 					${size_str}
		// 	// 				</div>`;
		// };
		// $('#legends').html(legends_html);

	});

	// 默认绘制第一项的图
	$('.pcaking-result-tr').each(function(idx, dom) {
		if (idx === 0) {
			$(dom).trigger('click');
		}
	});

}

var clear = function() {

	$('#progress-footer').hide();
	$('#progress-footer-2').hide();

	$('#pcaking-result-table-body').empty();
	$(".plotly_show").empty();
	
	$('#legend-div').hide();
	$('#div-checklist').hide();

	$('.img-div').each(function(idx, divDom) {

		$(divDom).find('img').each(function(index, dom) {

			$(dom).attr('src', '#');

		});

	});

}


/**
 * 根据设置重新绘制图像
 * @param {*} heaps_str 
 * @param {*} packer_str 
 * @param {*} figure_type: 1：按照item种类绘图，默认方式，2：绘制热力图，3：着重绘制某一类item
 * @param {*} use_plotly 
 */
var refreshFigures = function (heaps_str, packer_str, figure_type, use_plotly) {
	
	$.blockUI({
		message: "<span>绘图中...</span>",
		css: {
			"font-size": "30px",
			"font-weight": "bold"
		}
	});
	
	$.ajax({
		type: "POST",
		url: plotHost,
		contentType: "application/json",
		dataType: "json",
		data: JSON.stringify({
			heaps: heaps_str,
			packer: packer_str,
			figure_type: figure_type,
			use_plotly: use_plotly
		}),
		async: true,
		success: function(result) {
			$.unblockUI();
			
			console.log(result);
			images = result.base64;
			if (imageType === 'base64') {
				$('.image_show').show();
				$('.plotly_show').hide();
				
				let divs = $('.img-div');
				divs.each(function(index, dom) {
				
					if (index < 4) {
						$(dom).find('img').attr('src', `data:image/png;base64,${result.base64[index + (current_page - 1) * 4]}`);
					}
				
				});
			}
			else if (imageType === 'plotly') {
				$('.image_show').hide();
				$('.plotly_show').show();
				$('.plotly_show').html(result.plotly_html[current_page - 1]);
			}
			
			$.ajax({
				type: "POST",
				url: serverHost + "export_detail",
				xhrFields: {
				        responseType: 'blob'  // 设置响应类型为二进制数据
				      },
				data: JSON.stringify({
					heaps: heaps_str,
					packer: packer_str,
					images: result.car_image
				}),
				async: true,
				success: function(data) {
					console.log(data);
					// 创建一个隐藏的<a>标签，用于触发文件下载
					var a = document.createElement('a');
					var url = window.URL.createObjectURL(data);
					a.href = url;
					a.download = 'file.xlsx';
					a.style.display = 'none';
					document.body.appendChild(a);
					a.click();
					window.URL.revokeObjectURL(url);
					$(a).remove();
				}
			});
			
		}
	});
	
}


$('#hot-switch').change(function() {
	// current_page = 1;
	// setPageView(totalPage);
	
	// console.log($(this).is(':checked'), current_tr_id);
	
	let figure_type = 1;
	$('#legend-div').find('img').attr('src', './icon/legend1.png');
	$('#legend-div').find('img').attr('width', '150px');
	$('#legend-div').css('right', '0%');
	if ($(this).is(':checked')) {
		$('#legend-div').find('img').attr('src', './icon/legend3.png');
		$('#legend-div').find('img').attr('width', '70px');
		$('#legend-div').css('right', '3%');
		figure_type = 2;
	}
	
	if (current_tr_id === -1) {
		return;
	}
	refreshFigures(pack_results[current_tr_id]['heaps'], pack_results[current_tr_id]['packer'], figure_type, plotly_3d);
	
});

$('#image-type-switch').on('change', function () {
	
	let figure_type = 1;
	if ($('#hot-switch').is(':checked')) {
		figure_type = 2;
	}
	
	if ($(this).is(':checked')) {
		imageType = 'plotly';
	} else {
		imageType = 'base64';
	}
	
	if (current_tr_id === -1) {
		return;
	}
	
	refreshFigures(pack_results[current_tr_id]['heaps'], pack_results[current_tr_id]['packer'], figure_type, plotly_3d);
	
});

